package handler

import (
	"context"
	"encoding/json"
	"qld2devservice/models"
	dev "qld2devservice/proto"
	"qld2devservice/service"
	"qld2devservice/utils"
	"time"
)

// apiController 控制器
type handlerDevCloseForceController struct{}

func NewDevCloseForceController() dev.DevCloseForceServer {
	return &handlerDevCloseForceController{}
}

// OutLetCloseForce 关闭设备
func (that *handlerDevCloseForceController) OutLetCloseForce(ctx context.Context, p *dev.OutLetCloseForceRequest) (res *dev.OutLetCloseForceResponse, err error) {
	utils.MyPrint(utils.PRINT_INFO, "OutLetCloseForce request", utils.TransProtoToJson(p))
	res = &dev.OutLetCloseForceResponse{}
	if err = service.RedisSave(p.SnNum+"/operateFlag", ""); err != nil {
		return res, utils.WrapError(err, "OutLetCloseForce: redis保存operateFlag失败")
	}
	defer func() {
		orderSn := res.OrderSn
		time.AfterFunc(5*time.Second, func() {
			b, err2 := json.Marshal(map[string]interface{}{
				"orderSn": orderSn,
				"retCode": 200,
			})
			if err2 != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err2, "OutLetClose:json字符串转换获取失败"))
			}
			if err = service.MqttNoticeSend(p.SnNum+"/orderFinish", string(b)); err != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err, "OutLetClose:orderFinish信息推送失败"))
			}
		})
		if err2 := service.RedisDel(p.SnNum + "/operateFlag"); err2 != nil {
			utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err2, "OutLetCloseForce: redis删除operateFlag失败"))
		}
		if err != nil {
			service.PutErrorMsg("OutLetCloseForce"+err.Error(), p.SnNum, service.UserControlErr)
			utils.MyPrint(utils.PRINT_ERROR, err.Error())
			err = nil
			res.CloseFlag = 1
			res.CloseMsg = "操作错误"
		}
		utils.MyPrint(utils.PRINT_INFO, "OutLetCloseForce response", utils.TransProtoToJson(res))
	}()

	if qldOutlets, err2 := models.GetQldOutletsBySnNum(p.SnNum); err2 != nil {
		return res, utils.WrapError(err2, "OutLetCloseForce: 1，获取数据设备信息失败")
	} else if len(qldOutlets) == 0 {
		return res, nil
	} else {
		if qldOutlets[0].Type == 6 {
			res.TimeOut, res.CloseFlag, res.Amount, res.Electricity, res.Duration, res.OrderSn, res.AmountRecord, res.CloseMsg, err = service.DeviceForceClose(p.UserID, p.SnNum)
		} else if qldOutlets[0].Type == 8 {
			res.TimeOut, res.CloseFlag, res.Amount, res.Electricity, res.Duration, res.OrderSn, res.AmountRecord, res.CloseMsg, err = service.StopChargingSpw(p.UserID, p.SnNum)
		} else {
			res.TimeOut, res.CloseFlag, err = service.OperateDevice(p.SnNum, service.OperateDeviceCloseIOValue, 0, 2, 15)
			if err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce:2，控制设备失败6")
			}
			if err2 := models.SetQldOutletValue(p.SnNum, 0, 0); err2 != nil {
				return res, utils.WrapError(err2, "OutLetCloseForce:3，更新数据库失败")
			}
			if res.Duration, err = service.AnalyzeDevDurationGet(p.SnNum + "/openTime"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce:7，获取订单时间失败")
			}

			if electricity, err2 := service.AnalyzeDevPowerElectricityGet(p.SnNum); err2 != nil {
				return res, utils.WrapError(err2, "OutLetCloseForce:9，获取订单电量失败")
			} else {
				res.Electricity = float32(electricity)
			}
			if res.OrderSn, err = service.SpecialOrderSnGet(p.SnNum+"/orderSn", ""); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce:10，活动订单sn失败")
			}

			//if res.Amount, err = service.AnalyzeDevPowerAmountGet(p.SnNum); err != nil {
			//	return res, utils.WrapError(err, "OutLetCloseForce:8，获取订单金额失败")
			//}
			//timetype, err := service.RedisGet(p.SnNum+"/timeType", "0")
			//if timetype == "2" {
			//	if res.AmountRecord, err = service.RedisGet(p.SnNum+"/amountRecord", "0"); err != nil {
			//		return res, utils.WrapError(err, "OutLetClose关闭设备:10，活动订单sn失败")
			//	}
			//} else {
			//	if res.AmountRecord, err = service.CalculateAmountRecord(p.SnNum); err != nil {
			//		return res, utils.WrapError(err, "OutLetClose关闭设备:10，活动订单sn失败")
			//	}
			//}
			if res.Amount, res.AmountRecord, err = service.CalculateAmountType(p.SnNum); err != nil {
				return res, utils.WrapError(err, "OutLetClose关闭设备:8，获取订单金额失败")
			}

			if err = service.RedisDel(p.SnNum + "/userId"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 5，etcd删除userId失败")
			}
			if err = service.DelUserIdAndSnNum(p.UserID, p.SnNum); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 6，etcd删除userId_snNum失败")
			}
			if err = service.RedisSave(p.SnNum+"/electricity", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 12，electricity清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/electricity", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/power", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 13，power清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/power", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/voltage", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，voltage清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/voltage", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/current", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 15，current清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/current", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/amount", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 16，amount清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/amount", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/remainAmount", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 17，remainAmount清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/remainAmount", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/soc", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 18，soc清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/soc", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/dSoc", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 19，dSoc清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/dSoc", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/timeLeft", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 20，timeLeft清零etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/timeLeft", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 14，electricityLast清零redis失败")
			}
			if err = service.RedisSave(p.SnNum+"/isWorking", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: 4，isWorking保存到etcd失败")
			}
			if err = service.MqttNoticeSend(p.SnNum+"/isWorking", "0"); err != nil {
				return res, utils.WrapError(err, "OutLetCloseForce: isWorking推送失败")
			}
			//  new add
			if err = service.RedisSave(p.SnNum+"/restart", "0"); err != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err, "restart 清理失败"))
			}
			if err = service.RedisSave(p.SnNum+"/stoptime", "0"); err != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err, "stoptime 清理失败"))
			}
			if err = service.RedisSave(p.SnNum+"/stepelec", "0"); err != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err, "stepelec 清理失败"))
			}
			if err = service.RedisSave(p.SnNum+"/duration", "0"); err != nil {
				utils.MyPrint(utils.PRINT_ERROR, utils.WrapError(err, "stepelec 清理失败"))
			}
		}
	}
	return res, nil
}
